import React, { useRef, useState, useEffect, useCallback } from "react";
import { Divider, Col, Form, Input, Button, Row, message, Spin, Tabs, Space, Checkbox, Tree, Card, Modal, Steps, Select, TreeSelect, DatePicker, } from 'antd';
import { UploadPhotoToServer, WangEditor5, XxDatePicker, XxSelect, XxtreeSelect, XxUploadPhotoList, } from '@/ui';
import { PlusOutlined, FolderOpenOutlined, DownOutlined, CloseOutlined, DoubleRightOutlined } from '@ant-design/icons';
import { useLocation } from "react-router-dom";
import styls from './editArticle.module.scss'
import styles from "./editProduct.module.scss";
import { brandApi, cateApi, classApi, prodListApi, propertyApi } from "@/api";
import { errorAlert } from "@/common/methods";
import EditSkuTable from "@/ui/editSkusTable";
import { PageContainer } from "@ant-design/pro-components";
import { mobxState } from "@/data";
import dayjs from "dayjs";
const { TextArea } = Input;



/**
 * 
 * @description 新建|编辑产品页面
 * @param {} param0 
 * @returns 
 */
const EditProduct = () => {
    const skuRef = useRef();
    /**@description 行业属性列表 */
    const [propertyList, setPropertyList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [currentStep, setCurrentStep] = useState(1);
    const [selectedIndustry, setSelectedIndustry] = useState('');
    const [filteredBrands, setFilteredBrands] = useState([]);
    /**@description 商品分类列表 */
    const [categoryList, setCategoryList] = useState([]);

    const [product, setProduct] = useState({});
    const [action, setAction] = useState("add");
    const location = useLocation();
    const [form] = Form.useForm();

    /**
 * 获取商品分类列表数据
 * @description 通过调用分类API获取分类列表,并更新分类列表状态
 * @async
 * @function getCategoryList
 * @returns {Promise<void>} 无返回值,仅更新状态
 */
    const getCategoryList = async () => {
        const { data } = await cateApi.getCateList();
        if (data) {
            setCategoryList([...data[0].children])
        }
    }
    /**@description 获取行业属性列表 */
    const getPropertyList = async (classId) => {
        try {
            const { data } = await propertyApi.getPropertyList({ pageSize: 1000, current: 1, classId: classId });
            if (data.list && data.list.length > 0) {
                setPropertyList(data.list)
            }
        } catch (error) {
        }
    }


    const getDetail = async (id) => {
        try {
            const { data, code, msg } = await prodListApi.getProdDetail(id);
            const {
                masterImages,
                title,
                brandId,
                shelfTime,
                specContent,
                cateId, intro,
                description, price,
                sellPrice,
                sku,
                professionId,
                seoTitle,
                seoDescription,
                seoKeyWords,
                seoUrl,
                takeDown,
                snapshot,
            } = data;
            console.log("拿到详情", data)
            setProduct(data)
            form.setFieldsValue({
                intro,
                professionId,
                id,
                price, sellPrice,
                masterImages: JSON.parse(masterImages),
                title,
                cateId,
                description,
                brandId,
                shelfTime: dayjs(shelfTime),
                seoTitle,
                seoDescription,
                seoKeyWords,
                seoUrl,
                takeDown,
                snapshot,
            })
            console.log("拿到详情的sku和规格配置：", sku, specContent)
            skuRef.current.initData(sku || [], specContent || [])
        } catch (error) {
            errorAlert("获取详情失败：" + error)
        }
    }


    useEffect(() => {
        console.log("location:", location)

        if (location?.state) {
            console.log("location", location?.state)
            const { id = null, type = "add" } = location?.state;
            if (id && type === "update") {
                setAction("update")
                setCurrentStep(1)
                getDetail(id)
            }
            if (product.professionId) {
                getPropertyList(product.professionId);
            }
        }

    }, [location])





    /**@description 保存文章数据 */
    const saveData = async (values) => {
        const { data, code, msg } = await prodListApi.createProd({ ...values });
        if (code === 0) {
            message.success("保存成功")
            setTimeout(() => {
                console.log("跳转列表页")
                mobxState.closeTab("product_type_edit_form")
            }, 1000)
        }

    }




    // 点击提交
    const submit = () => {
        console.log("表单校验：", skuRef.current.getData())
        const { submitList, specContent } = skuRef.current.getData()
        form.validateFields().then(values => {
            console.log("表单数据：", values)
            let paramsFormData = {
                ...product,
                ...values,
                sku: submitList,
                specContent: specContent,
                shelfTime: dayjs(values.shelfTime).format("YYYY-MM-DD HH:mm:ss")

            }
            saveData(paramsFormData)
        }).catch(error => {
            console.log("校验失败：", error)
        })
    }




    const BasicInfo = () => {
        return (
            <Row gutter={24}>
                <Col span={24} style={{ display: "none" }}>
                    <Form.Item name='id' label="id">
                        <Input />
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item name='title' label="标题">
                        <Input />
                    </Form.Item>
                </Col>
                <Col span={24}>

                    <Form.Item label="上传图片"
                        name={"masterImages"}
                    >
                        <UploadPhotoToServer />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item name='cateId' label="商品分类">
                        <XxtreeSelect treeData={categoryList} fieldNames={{
                            label: "cateName",
                            value: "id",
                            children: 'children'
                        }} />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item name='shelfTime' label="上架时间">
                        <DatePicker placeholder="上架时间" format="YYYY-MM-DD HH:mm:ss" showTime pick="date" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="商品价格" name='sellPrice'>
                        <Input prefix="￥" suffix="元" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="划线价格" name="price" >
                        <Input prefix="￥" suffix="元" />
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item name='intro' label="商品简介">
                        <TextArea />
                    </Form.Item>
                </Col>
            </Row>
        )
    }





    const SEOConfig = () => {
        const optionsWithDisabled = [{
            label: "允许搜索引擎搜索快照",
            value: "takeDown"
        },
        {
            label: "允许搜索引擎收录",
            value: "snapshot"
        }
        ]
        return (
            <Col span={24} >
                <Form.Item name="seoTitle" label="SEO标题">
                    <Input />
                </Form.Item>
                <Form.Item name="seoDescription" label="meta描述">
                    <TextArea />
                </Form.Item>
                <Form.Item name="seoKeyWords" label="关键词">
                    <Input />
                </Form.Item>
                <Form.Item name="seoUrl" label="URL别名">
                    <Input />
                </Form.Item>
                <Form.Item name="searchEngine" label="搜索引擎">
                    <Checkbox.Group
                        options={optionsWithDisabled}
                        defaultValue={['takeDown', 'snapshot']}
                    >
                        <Row gutter={24}>
                            {
                                optionsWithDisabled.map((item, key) => (
                                    <>
                                        <Col span={24} key={key}>
                                            <Checkbox value={item.value}>{item.label}</Checkbox>
                                        </Col>
                                        <br />
                                    </>
                                ))
                            }
                        </Row>
                    </Checkbox.Group>
                </Form.Item>

            </Col>

        )
    }



    const cardStyle = {
        // backgroundColor: "#f0f2f5",
        marginBottom: 20
    }


    const [state, setState] = useState({
        data: [{
            children: []
        }],
        totalCount: 0
    })



    /**@description 查找品牌列表 */
    const getBrandList = async (calssId) => {
        try {
            setLoading(true);
            const { data, code, msg } = await brandApi.getBrandList({ pagesize: 1000, current: 1, calssId });
            if (data?.list?.length > 0) {
                setFilteredBrands(data.list.map(item => ({
                    label: item.brandName,
                    value: item.id
                })))
            }

        } catch (error) {

        } finally {
            setLoading(false);
        }
    }


    /**@description 查找行业列表 */
    const getList = async () => {
        try {
            setLoading(true);
            const { data, code, msg } = await classApi.getClassList({ pagesize: 1000, current: 1 });
            setState({
                data: data.list,
                totalCount: data.totalCount || 0
            })
        } catch (error) {
            console.log("错误：", error)
        } finally {
            setLoading(false);
        }
    }

    useEffect(() => {
        getCategoryList()
        getList();
        getBrandList(null);
    }, [])








    const handleIndustryChange = (value, options) => {
        setSelectedIndustry(options.id);
        form.setFieldValue('brandId', undefined);
        getBrandList(options.id);
    };



    return (
        <>
            <PageContainer
                style={{
                    display: "flex",
                    flexDirection: "column",
                    overflowY: "auto"
                }}
            >
                <Form
                    layout="vertical"
                    form={form}
                    wrapperCol={24}
                    className="edit-form"
                >
                    <div className={styls.editStyles}>
                        <div className="header">
                            <span></span>
                            <Space>
                                {currentStep === 0 ? null : <Button onClick={() => setCurrentStep(0)}>上一步</Button>}
                                <Button type="primary" onClick={submit}>{currentStep === 0 ? "下一步" : "保存"}</Button>
                            </Space>
                        </div>
                        <div className="center">
                            <div className="edit-content">

                                <Card
                                    style={cardStyle}>
                                    <Row gutter={24}>

                                        <Col span={12}>
                                            <Form.Item
                                                label="选择行业"
                                                name="professionId"
                                                rules={[{ required: true, message: '请选择行业' }]}
                                            >
                                                <TreeSelect
                                                    placeholder="请选择商品所属行业"
                                                    treeData={state.data[0].children || []}
                                                    onSelect={handleIndustryChange}
                                                    fieldNames={{
                                                        label: "className",
                                                        value: "id",
                                                    }}
                                                />
                                            </Form.Item>
                                        </Col>
                                        <Col span={12}>
                                            <Form.Item
                                                label="选择品牌"
                                                name="brandId"
                                                rules={[{ required: true, message: '请选择品牌' }]}
                                            >
                                                <Select
                                                    placeholder="请选择商品品牌"
                                                    options={filteredBrands}
                                                />
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Card>
                                <Card
                                    style={cardStyle}>
                                    <BasicInfo />
                                </Card>
                                <Card style={cardStyle}>
                                    {/* <EditSkuTable onRef={skuRef} /> */}
                                </Card>

                                <Form.Item name="description" className="content-formItem">
                                    <WangEditor5 />
                                </Form.Item>
                                <Card style={cardStyle}>
                                    <SEOConfig />
                                </Card>

                            </div>
                        </div>
                    </div>
                </Form>
            </PageContainer>





        </>
    )


}

export default EditProduct;